package com.bihu.bihudemo.auth.compoent;


import com.alibaba.fastjson.JSON;
import com.bihu.bihudemo.entity.User;
import com.bihu.bihudemo.result.AuMsg;
import com.bihu.bihudemo.result.Result;
import com.bihu.bihudemo.service.UserService;
import com.bihu.bihudemo.utils.redis.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//自定义登录成功处理,生成Token
@Component
public class CustomAuthenticationSuccessHandler  implements AuthenticationSuccessHandler {

    @Resource
    RedisUtil redisUtil;

    @Resource
    UserService userService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {


        //取得用户信息
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();


        //先去缓存中取得token
        String token = (String) redisUtil.get("token_"+userDetails.getUsername());
        Result result1;
        User user = userService.getUserByUserName(userDetails.getUsername());

        //用户第一次登录，就根据用户名生成token，并且放入缓存中。
        if (token == null) {
            String generatedToken = new JwtTokenUtil().generateToken(userDetails);
            redisUtil.set("token_" + userDetails.getUsername(), generatedToken);
            AuMsg auMsg = new AuMsg(user.getUsername(), user.getId(), generatedToken);
            result1 = Result.ok().put("userinfo", auMsg);
        } else {
            AuMsg auMsg = new AuMsg(user.getUsername(), user.getId(), token);
            result1 = Result.ok().put("userinfo", auMsg);
        }
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result1));

    }
}
